package com.luoye.lj.platform.service.impl;


import com.luoye.lj.platform.constant.ServiceExceptionConstants;
import com.luoye.lj.platform.dao.IMuserserviceDao;
import com.luoye.lj.platform.model.domain.AuthInfo;
import com.luoye.lj.platform.model.domain.RUnitInfo;
import com.luoye.lj.platform.model.domain.RoleInfo;
import com.luoye.lj.platform.model.domain.manage.ManageLog;
import com.luoye.lj.platform.model.domain.manage.ManageLogCollection;
import com.luoye.lj.platform.model.domain.manage.ManageLogSearchCondition;
import com.luoye.lj.platform.model.domain.muser.*;
import com.luoye.lj.platform.model.enums.DeleteMark;
import com.luoye.lj.platform.service.IMuserservice;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created with IntelliJ IDEA.
 * User: Dave Liu
 * Date: 15-9-28
 * Time: 下午5:36
 * To change this template use File | Settings | File Templates.
 */
@Service
public class MuserserviceImpl implements IMuserservice {
    private static Logger logger = LoggerFactory.getLogger(MuserserviceImpl.class);

    @Autowired
    private IMuserserviceDao muserserviceDao;

    @Override
    public MUserDetail getUserDetail(String username) {
        //先查询用户
        MUserInfo mUserInfo=muserserviceDao.getUserByName(username);
        if(mUserInfo!=null){
            if(mUserInfo.getDelmark()== DeleteMark.DELETED.getCode()){//已经删除了
                return null;
            }

            List<RoleInfo> roleInfoList=muserserviceDao.getRolesByUid(mUserInfo.getId());
            Map<String, AuthInfo> authInfoMap = new HashMap<String, AuthInfo>();
            if(!CollectionUtils.isEmpty(roleInfoList)) {
                //查询权限列表
                for (RoleInfo roleInfo : roleInfoList) {
                    List<AuthInfo> authInfoListTemp = muserserviceDao.getAuthsByRid(roleInfo.getId());
                    if(!CollectionUtils.isEmpty(authInfoListTemp)){
                        for(AuthInfo authInfo:authInfoListTemp){
                            authInfoMap.put(authInfo.getId()+"",authInfo);
                        }
                    }
                }

            }

            MUserDetail mUserDetail=new MUserDetail();
            mUserDetail.setId(mUserInfo.getId());
            mUserDetail.setUsername(mUserInfo.getUsername());
            mUserDetail.setRealName(mUserInfo.getRealName());
            mUserDetail.setPasswd(mUserInfo.getPasswd());
            mUserDetail.setDefaultUrl(mUserInfo.getDefaultUrl());
            mUserDetail.setEmail(mUserInfo.getEmail());
            mUserDetail.setMobilePhone(mUserInfo.getMobilePhone());
            mUserDetail.setStatus(mUserInfo.getStatus());
            mUserDetail.setLastLoginTime(mUserInfo.getLastLoginTime());
            mUserDetail.setRoleInfoList(roleInfoList);
            if(!authInfoMap.isEmpty()) {
                List<AuthInfo> authInfoList=new ArrayList<AuthInfo>();
                authInfoList.addAll(authInfoMap.values());
                mUserDetail.setAuthInfoList(authInfoList);
            }

            return mUserDetail;
        }
        return null;
    }

    @Override
    public List<RoleInfo> getRoles() {
        return muserserviceDao.getAllRole();
    }

    @Override
    @Transactional
    public MUserInfo addUser(MUserSaveInfo mUserSaveInfo) {
        //查询是否已经添加
        MUserInfo mUserInfo=muserserviceDao.getUserByName(mUserSaveInfo.getUsername());
        if(mUserInfo!=null){
            if(mUserInfo.getDelmark()==DeleteMark.OK.getCode()){
                throw ServiceExceptionConstants.USER_ALREADY_EXIST;
            }else{//更新这条记录
                mUserInfo.setPasswd(mUserSaveInfo.getPasswd());
                mUserInfo.setDefaultUrl(mUserSaveInfo.getDefaultUrl());
                mUserInfo.setRealName(mUserSaveInfo.getRealName());
                mUserInfo.setEmail(mUserSaveInfo.getEmail());
                mUserInfo.setMobilePhone(mUserSaveInfo.getMobilePhone());
                mUserInfo.setStatus(mUserSaveInfo.getStatus());
                mUserInfo.setDelmark(DeleteMark.OK.getCode());
                int rowCount=muserserviceDao.updateUser(mUserInfo);
                if(rowCount!=1){
                    throw ServiceExceptionConstants.SAVE_FAILED;
                }
            }
        }else{
            //插入一条用户记录到数据库
            mUserInfo=new MUserInfo();
            mUserInfo.setUsername(mUserSaveInfo.getUsername());
            mUserInfo.setPasswd(mUserSaveInfo.getPasswd());
            mUserInfo.setDefaultUrl(mUserSaveInfo.getDefaultUrl());
            mUserInfo.setRealName(mUserSaveInfo.getRealName());
            mUserInfo.setEmail(mUserSaveInfo.getEmail());
            mUserInfo.setMobilePhone(mUserSaveInfo.getMobilePhone());
            mUserInfo.setStatus(mUserSaveInfo.getStatus());
            int rowCount=muserserviceDao.insertUser(mUserInfo);
            if(rowCount!=1){
                throw ServiceExceptionConstants.SAVE_FAILED;
            }
        }

        //更新关联角色
        mUserSaveInfo.setId(mUserInfo.getId());
        muserserviceDao.delUrr(mUserSaveInfo.getId());
        muserserviceDao.addUrr(mUserSaveInfo);

        return mUserInfo;
    }

    @Override
    @Transactional
    public MUserInfo modifyUser(MUserSaveInfo mUserSaveInfo) {
        logger.info("mUserSaveInfo->"+mUserSaveInfo);
        //查询是否已经添加
        MUserInfo mUserInfo=muserserviceDao.getUserById(mUserSaveInfo.getId());
        logger.info("mUserInfo->"+mUserInfo);
        if(mUserInfo==null||mUserInfo.getDelmark()==DeleteMark.DELETED.getCode()){
            throw ServiceExceptionConstants.USER_NOT_FOUND;
        }

        //更新MUserInfo
        mUserInfo=new MUserInfo();
        mUserInfo.setId(mUserSaveInfo.getId());
        mUserInfo.setUsername(mUserSaveInfo.getUsername());
        mUserInfo.setPasswd(mUserSaveInfo.getPasswd());
        mUserInfo.setDefaultUrl(mUserSaveInfo.getDefaultUrl());
        mUserInfo.setRealName(mUserSaveInfo.getRealName());
        mUserInfo.setEmail(mUserSaveInfo.getEmail());
        mUserInfo.setMobilePhone(mUserSaveInfo.getMobilePhone());
        mUserInfo.setStatus(mUserSaveInfo.getStatus());
        mUserInfo.setLastLoginTime(mUserSaveInfo.getLastLoginTime());
        int rowCount=muserserviceDao.updateUser(mUserInfo);
        if(rowCount!=1){
            throw ServiceExceptionConstants.SAVE_FAILED;
        }

        //更新关联角色
        List<Long> roleIds=mUserSaveInfo.getRidList();
        if(roleIds!=null) {
            muserserviceDao.delUrr(mUserSaveInfo.getId());
            muserserviceDao.addUrr(mUserSaveInfo);
        }

        return mUserInfo;  //To change body of implemented methods use File | Settings | File Templates.
    }

    @Override
    public MUserDetail getUserDetail(long id) {
        //先查询用户
        MUserInfo mUserInfo=muserserviceDao.getUserById(id);
        if(mUserInfo!=null){
            if(mUserInfo.getDelmark()== DeleteMark.DELETED.getCode()){//已经删除了
                return null;
            }

            List<RoleInfo> roleInfoList=muserserviceDao.getRolesByUid(mUserInfo.getId());
            Map<String, AuthInfo> authInfoMap = new HashMap<String, AuthInfo>();
            if(!CollectionUtils.isEmpty(roleInfoList)) {
                //查询权限列表
                for (RoleInfo roleInfo : roleInfoList) {
                    List<AuthInfo> authInfoListTemp = muserserviceDao.getAuthsByRid(roleInfo.getId());
                    if(!CollectionUtils.isEmpty(authInfoListTemp)){
                        for(AuthInfo authInfo:authInfoListTemp){
                            authInfoMap.put(authInfo.getId()+"",authInfo);
                        }
                    }
                }

            }

            MUserDetail mUserDetail=new MUserDetail();
            mUserDetail.setId(mUserInfo.getId());
            mUserDetail.setUsername(mUserInfo.getUsername());
            mUserDetail.setRealName(mUserInfo.getRealName());
            mUserDetail.setPasswd(mUserInfo.getPasswd());
            mUserDetail.setDefaultUrl(mUserInfo.getDefaultUrl());
            mUserDetail.setEmail(mUserInfo.getEmail());
            mUserDetail.setMobilePhone(mUserInfo.getMobilePhone());
            mUserDetail.setStatus(mUserInfo.getStatus());
            mUserDetail.setLastLoginTime(mUserInfo.getLastLoginTime());

            mUserDetail.setRoleInfoList(roleInfoList);
            if(!authInfoMap.isEmpty()) {
                List<AuthInfo> authInfoList=new ArrayList<AuthInfo>();
                authInfoList.addAll(authInfoMap.values());
                mUserDetail.setAuthInfoList(authInfoList);
            }

            return mUserDetail;
        }
        return null;
    }

    @Override
    public ManageLog insertLog(ManageLog manageLog) {
        int rowCount=muserserviceDao.insertLog(manageLog);
        return manageLog;
    }

    @Override
    public MUserDetailCollection searchByCondition(MUserDetailSearchCondition muserDetailSearchCondition) {
        muserDetailSearchCondition.setDelmark(0);//只查询出没有删除的
        MUserDetailCollection list = muserserviceDao.searchUserDetailByCondition(muserDetailSearchCondition);
        System.err.println(list);
        return muserserviceDao.searchUserDetailByCondition(muserDetailSearchCondition);
    }

    @Override
    public boolean delUser(long id) {
        //查询是否已经存在
        MUserInfo mUserInfo=muserserviceDao.getUserById(id);
        if(mUserInfo==null||mUserInfo.getDelmark()==DeleteMark.DELETED.getCode()){
            throw ServiceExceptionConstants.USER_NOT_FOUND;
        }
        //设置delete标签
        mUserInfo.setDelmark(DeleteMark.DELETED.getCode());
        int rowCount=muserserviceDao.updateUser(mUserInfo);
        if(rowCount!=1){
            throw ServiceExceptionConstants.SAVE_FAILED;
        }
        return true;
    }

    @Override
    public ManageLogCollection searchManageLog(ManageLogSearchCondition manageLogSearchCondition) {
        logger.info("manageLogSearchCondition->"+manageLogSearchCondition);
        return muserserviceDao.searchManageLogByCondition(manageLogSearchCondition);
    }

    @Override
    public MUserInfo modifyUserInfo(MUserInfo mUserInfo) {
        if(mUserInfo==null){
            throw ServiceExceptionConstants.USER_NOT_FOUND;
        }
        //查询是否已经添加
        MUserInfo mUserInfoTemp=muserserviceDao.getUserById(mUserInfo.getId());
        if(mUserInfoTemp==null||mUserInfoTemp.getDelmark()==DeleteMark.DELETED.getCode()){
            throw ServiceExceptionConstants.USER_NOT_FOUND;
        }

        //更新MUserInfo
        int rowCount=muserserviceDao.updateUser(mUserInfo);
        if(rowCount!=1){
            throw ServiceExceptionConstants.SAVE_FAILED;
        }

        return mUserInfo;
    }

}
